package com.yuanfeng.commoms.exception;


import com.yuanfeng.commoms.util.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.RejectedExecutionException;

@RestControllerAdvice

@Slf4j
public class SpringExceptionHandler {
	
	private static final Logger LOG = LoggerFactory.getLogger(SpringExceptionHandler.class);

	/**
	 * 全局处理Exception 错误的情况下返回2
	 * 
	 * @param ex
	 * @param
	 * @return
	 * @throws IOException
	 */
	@ExceptionHandler(value = { Exception.class })
	public ResponseResult handlerException(final Exception ex, final HttpServletRequest request) throws IOException {
		ResponseResult result = null;
		try {

			if (ex instanceof UserDefinedException) {

				
				result = ResponseResult.success(((UserDefinedException) ex).getErrorCode().getErrorCode(), null,
						((UserDefinedException) ex).getErrorCode().getErrorMsg());

			} else if (ex instanceof BadSqlGrammarException || ex instanceof MyBatisSystemException
					|| ex instanceof HandlerExceptionResolver) {
				result = ResponseResult.success(GlobalExceptionEnum.MYSQL_EXCEPTION.getErrorCode(), null,
						GlobalExceptionEnum.MYSQL_EXCEPTION.getErrorMsg());
			} else if (ex instanceof RejectedExecutionException) {
				result = ResponseResult.success(GlobalExceptionEnum.BLOCKING_EXCEPTION.getErrorCode(), null,
						GlobalExceptionEnum.BLOCKING_EXCEPTION.getErrorMsg());
			} else {
				result = ResponseResult.success(GlobalExceptionEnum.SYSTEM_ERROR.getErrorCode(), null,
						GlobalExceptionEnum.SYSTEM_ERROR.getErrorMsg());
			}

		} catch (Exception e) {
			result = ResponseResult.success(GlobalExceptionEnum.SYSTEM_ERROR.getErrorCode(), null,
					GlobalExceptionEnum.SYSTEM_ERROR.getErrorMsg());
		}
		ex.printStackTrace();
		return result;
	}
}
